package com.logic.config.netty.web.service;


import java.util.*;

import com.logic.config.netty.web.util.SessionHolder;
import lombok.extern.slf4j.Slf4j;


import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import static com.logic.config.netty.web.constant.SessionConstant.CHANEL_INFO_KEY;

@Slf4j
public class WebSocketInfoService {

    /**
     * 清除会话信息
     * @param channel
     */
    public void clearSession(Channel channel) {
        Object userId = channel.attr(CHANEL_INFO_KEY).get().getUserId();
        // 清除会话信息
        SessionHolder.channelGroup.remove(channel);
        SessionHolder.channelMap.remove(userId);
    }

    /**
     * 广播 ping 信息
     */
    public void sendPing() {
        TextWebSocketFrame tws = new TextWebSocketFrame("message");
        SessionHolder.channelGroup.writeAndFlush(tws);
    }

    /**
     * 从缓存中移除Channel，并且关闭Channel
     */
    public void scanNotActiveChannel() {
        Map<Object, Channel> channelMap = SessionHolder.channelMap;
        // 如果这个直播下已经没有连接中的用户会话了，删除频道
        if (channelMap.isEmpty()) {
            return;
        }
        for (Channel channel : channelMap.values()) {
            long lastHeartBeatTime = channel.attr(CHANEL_INFO_KEY).get().getLastLinkTime().getTime();
            long intervalMillis = (System.currentTimeMillis() - lastHeartBeatTime);
            if (!channel.isOpen()
                    || !channel.isActive()
                    || intervalMillis > 90000L) {
                channelMap.remove(channel);
                SessionHolder.channelGroup.remove(channel);
                if (channel.isOpen() || channel.isActive()) {
                    channel.close();
                }
            }
        }
    }
    
}
